<template>
    <div class="add">
        <el-input style="width: 300px; margin-right: 10px" v-model="key" type="textarea"></el-input>
        <el-button type="primary" plain @click="addMessage"
        >写留言</el-button>
    </div>
    <div class="mes-body">
        <div v-for="item in messageList.showList" class="mes-item">
            <span class="mes-data" style="background-color: aqua;">{{ item.ReaderName }}</span>
            <span class="mes-data" style="background-color: rgb(230, 187, 46);">{{ item.message }}</span>
            <span class="mes-data">{{ item.datetime }}</span>
        </div>
        
    </div>
    <el-pagination
      class="page"
      :page-size="4"
      v-model:current-page="page"
      :total="messageList.data.length"
      layout="total,prev, pager, next,jumper"
    />
</template>

<script setup>
import {reactive, onBeforeMount,ref, watch} from 'vue'
import { get, pagination, put } from '../../stores/requestMethod'
import { ElMessage } from 'element-plus'

const loginAccount = JSON.parse(sessionStorage.getItem("loginAccount"))

const messageList = reactive({
    data : [],
    showList : []
})
const key = ref('')
const page = ref(1)
const addMessage = () =>{
    if(loginAccount == null){
        ElMessage('您需要登录才能留言哦')
        return
    }
    if(key.value == ''){
        ElMessage('请输入留言')
        return
    }
    let data = {
        ReaderID : loginAccount.id,
        ReaderName : loginAccount.name,
        message : key.value,
        
    }
    put('http://127.0.0.1:5000/messages',JSON.stringify(data),
        (res) => {
            ElMessage({
                message: res.msg,
                type : 'success'
            })
            key.value = ''
            getMessages()
        }
    )
    
}
const getMessages = () => {
    get('http://127.0.0.1:5000/messages',
        (res) => {
            messageList.data = res.data
            messageList.showList = pagination(4,page.value,JSON.parse(JSON.stringify(messageList.data)))
        }
    )
}
onBeforeMount(() => {
    getMessages()
})
watch(page, (value, oldValue) => {
  messageList.showList = pagination(
    4,
    value,
    JSON.parse(JSON.stringify(messageList.data))
  );
});
</script>

<style scoped>
.add{
    margin-top: 20px;
    margin-bottom: 20px;
    margin-left: 20px;
    text-align: left;
}
.page {
  position: relative;
  width: 50%;
  left: 40%;
  top: 10px;
}
.mes-body{
    width: 70%;
    margin-left: 15%;
    
    display: flex;
    flex-direction: column;
}
.mes-item{
    border: 2px solid #909399;
    display: flex;
    border-radius: 5px;
    flex-direction: column;
    margin: 5px 0;
}
.mes-data{
    height: 30px;
    line-height: 30px;
    margin: 5px 10px;
    border-radius: 10px;
    background-color: #909399;
}
</style>